package com.atguigu.daijia.common.annotations;

import com.atguigu.daijia.common.constant.RedisConstant;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.common.util.AuthContextHolder;
import io.netty.util.internal.StringUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
@Aspect
public class GuiguLoginAspect {

    @Autowired
    private RedisTemplate redisTemplate;


    @Pointcut("execution(* com.atguigu.daijia.*.controller.*.*(..)) && @annotation(GuiguLogin)")
    public void pt(){}


    @Around("pt()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        //1 获取request对象
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes)attributes;
        HttpServletRequest request = sra.getRequest();

        //2 从请求头获取token
        String token = request.getHeader("token");

        //3 判断token是否为空，如果为空，返回登录提示
        if(!StringUtils.hasText(token)){
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }

        //4 token不为空，查询redis对应用户id
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String id = (String) valueOperations.get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);

        //5 id判空，把用户id放到ThreadLocal里面
        if(StringUtils.hasText(id)){
            AuthContextHolder.setUserId(Long.valueOf(id));
        }

        //6 执行业务方法
        return proceedingJoinPoint.proceed();

    }
}
